<template>
<div class="square-container">
    <!-- 顶部标签页 -->
    <div class="top-tabs">
        <div class="tab" :class="{ active: topTab === 'follow' }" @click="topTab = 'follow'">关注</div>
        <div class="tab" :class="{ active: topTab === 'discover' }" @click="topTab = 'discover'">发现</div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar" @click="goToSearch" v-if="topTab === 'discover'">
        <van-icon name="search" />
        <span>搜索笔记/用户/话题</span>
    </div>

    <!-- 发现页内容 -->
    <div v-if="topTab === 'discover'">
        <van-pull-refresh v-model="isRefreshing" @refresh="onRefresh">
            <!-- 推荐圈子 -->
            <div class="circle-section">
                <div class="section-header">
                    <div class="section-title">推荐圈子</div>
                    <div class="section-more" @click="goToAllCircles">我加入的圈子</div>
                </div>
                <div class="circle-list">
                    <div v-for="(item, index) in circleList" :key="index" class="circle-item" @click="goToCircle(item)">
                        <div class="circle-icon">
                            <img :src="item.icon" :alt="item.name" />
                            <div class="circle-tag" v-if="item.tag">{{ item.tag }}</div>
                        </div>
                        <div class="circle-name">{{ item.name }}</div>
                    </div>
                </div>
            </div>

            <!-- 内容排序 -->
            <div class="sort-bar">
                <div class="sort-item" :class="{ active: sortType === 'hot' }" @click="sortType = 'hot'">热门</div>
                <div class="sort-item" :class="{ active: sortType === 'new' }" @click="sortType = 'new'">最新</div>
            </div>

            <!-- 内容列表 -->
            <div class="post-list">
                <div v-for="(item, index) in postList" :key="index" class="post-item">
                    <!-- 用户信息 -->
                    <div class="post-user" @click.stop="goToUser(item.userId)">
                        <img :src="item.userAvatar" alt="" class="user-avatar">
                        <div class="user-info">
                            <div class="user-name">{{ item.userName }}</div>
                            <div class="post-time">{{ item.postTime }} <span v-if="item.location">· {{ item.location
                                    }}</span></div>
                        </div>
                        <div class="more-btn">
                            <van-icon name="ellipsis" />
                        </div>
                    </div>

                    <!-- 帖子内容 -->
                    <div class="post-content" @click="goToDetail(item.id)">
                        <div v-if="item.tag" class="post-tag">#{{ item.tag }} · </div>
                        <div class="post-text">{{ item.content }}</div>
                    </div>

                    <!-- 帖子互动数据 -->
                    <div class="post-actions">
                        <div class="action-item" @click.stop="sharePost(item)">
                            <van-icon name="share-o" />
                            <span>分享</span>
                        </div>
                        <div class="action-item" @click.stop="commentPost(item)">
                            <van-icon name="comment-o" />
                            <span>{{ item.comments || 0 }}</span>
                        </div>
                        <div class="action-item" @click.stop="likePost(item)">
                            <van-icon :name="item.isLiked ? 'like' : 'like-o'" :class="{ 'liked': item.isLiked }" />
                            <span>{{ item.likes || 0 }}</span>
                        </div>
                    </div>
                </div>

                <!-- 加载更多 -->
                <div class="loading-more" v-if="postList.length > 0">
                    <van-loading size="24px" color="#1989fa">加载中...</van-loading>
                </div>
            </div>
        </van-pull-refresh>
    </div>

    <!-- 关注页内容 -->
    <div v-else-if="topTab === 'follow'">
        <van-pull-refresh v-model="isRefreshing" @refresh="onRefreshFollow">
            <div class="post-list">
                <div v-for="(item, index) in followList" :key="index" class="post-item">
                    <!-- 用户信息 -->
                    <div class="post-user" @click.stop="goToUser(item.userId)">
                        <img :src="item.userAvatar" alt="" class="user-avatar">
                        <div class="user-info">
                            <div class="user-name">{{ item.userName }}</div>
                            <div class="post-time">{{ item.createTime }} <span v-if="item.location">· {{ item.location
                                    }}</span></div>
                        </div>
                        <div class="more-btn">
                            <van-icon name="ellipsis" />
                        </div>
                    </div>

                    <!-- 帖子内容 -->
                    <div class="post-content" @click="goToDetail(item.id)">
                        <div v-if="item.tag" class="post-tag">#{{ item.tag }} · </div>
                        <div class="post-text">{{ item.content }}</div>
                        <div class="post-images" v-if="item.images && item.images.length > 0">
                            <img v-for="(img, imgIndex) in item.images" :key="imgIndex" :src="img" :alt="item.title" />
                        </div>
                    </div>

                    <!-- 帖子互动数据 -->
                    <div class="post-actions">
                        <div class="action-item" @click.stop="sharePost(item)">
                            <van-icon name="share-o" />
                            <span>分享</span>
                        </div>
                        <div class="action-item" @click.stop="commentPost(item)">
                            <van-icon name="comment-o" />
                            <span>{{ item.comments }}</span>
                        </div>
                        <div class="action-item" @click.stop="likePost(item)">
                            <van-icon :name="item.isLiked ? 'like' : 'like-o'" :class="{ 'liked': item.isLiked }" />
                            <span>{{ item.likes }}</span>
                        </div>
                    </div>
                </div>

                <!-- 空状态 -->
                <div v-if="followList.length === 0" class="empty-follow">
                    <van-empty description="暂无关注内容">
                        <template #image>
                            <img src="@/assets/empty-follow..jpg" />
                        </template>
                        <van-button round type="primary" class="empty-btn"
                            @click="topTab = 'discover'">去发现更多用户</van-button>
                    </van-empty>
                </div>

                <!-- 加载更多 -->
                <div class="loading-more" v-if="followList.length > 0">
                    <van-loading size="24px" color="#1989fa">加载中...</van-loading>
                </div>
            </div>
        </van-pull-refresh>
    </div>
</div>
</template>

<script>
export default {
    name: 'SquarePage',

    data() {
        return {
            topTab: 'discover', // 顶部标签：discover-发现，follow-关注
            sortType: 'hot', // 排序方式：hot-热门，new-最新
            isRefreshing: false,
            loading: false,
            postList: [], // 发现页帖子列表
            followList: [], // 关注页帖子列表
            location: {
                city: '北京市',
                district: '朝阳区',
                latitude: 39.92,
                longitude: 116.46
            },

            // 推荐圈子
            circleList: [
                { id: 1, name: 'AI Coding', icon: 'https://img01.yzcdn.cn/vant/cat.jpeg', tag: '99+' },
                { id: 2, name: '大模型LLM', icon: 'https://img01.yzcdn.cn/vant/apple-1.jpg', tag: '99+' },
                { id: 3, name: '服务端与云原生', icon: 'https://img01.yzcdn.cn/vant/apple-2.jpg', tag: '99+' },
                { id: 4, name: '前端开发圈', icon: 'https://img01.yzcdn.cn/vant/cat.jpeg', tag: '99+' }
            ]
        }
    },

    created() {
        this.loadPostList()
        this.getLocation()
    },

    methods: {
        // 跳转到搜索页
        goToSearch() {
            this.$router.push('/search')
        },

        // 跳转到所有圈子
        goToAllCircles() {
            this.$toast('查看我加入的圈子功能开发中')
        },

        // 跳转到圈子详情
        goToCircle(circle) {
            this.$toast(`圈子详情页开发中：${circle.name}`)
        },

        // 跳转到用户页面
        goToUser(userId) {
            this.$router.push(`/user/${userId}`)
        },

        // 跳转到帖子详情
        goToDetail(id) {
            this.$router.push(`/detail/${id}`)
        },

        // 分享帖子
        sharePost() {
            this.$toast('分享功能开发中')
        },

        // 评论帖子
        commentPost(post) {
            this.$router.push(`/detail/${post.id}`)
        },

        // 获取用户位置
        getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    position => {
                        this.location.latitude = position.coords.latitude
                        this.location.longitude = position.coords.longitude
                        this.reverseGeocode(position.coords.latitude, position.coords.longitude)
                    },
                    error => {
                        console.log('获取位置失败:', error)
                    }
                )
            }
        },

        // 反向地理编码
        reverseGeocode(lat, lng) {
            console.log('lat：' + lat)
            console.log('lng：' + lng)
            // 这里应该调用地图服务API，如高德、百度等
            // 为了简化，这里使用模拟数据
            const cities = ['北京市', '上海市', '广州市', '深圳市', '杭州市']
            const districts = ['朝阳区', '海淀区', '西湖区', '福田区', '黄浦区']

            this.location.city = cities[Math.floor(Math.random() * cities.length)]
            this.location.district = districts[Math.floor(Math.random() * districts.length)]
        },

        // 下拉刷新 - 发现页
        onRefresh() {
            setTimeout(() => {
                this.postList = []
                this.loadPostList()
                this.isRefreshing = false
                this.$toast('刷新成功')
            }, 1000)
        },

        // 下拉刷新 - 关注页
        onRefreshFollow() {
            setTimeout(() => {
                this.followList = []
                this.loadFollowList()
                this.isRefreshing = false
                this.$toast('刷新成功')
            }, 1000)
        },

        // 加载发现页帖子列表
        loadPostList() {
            if (this.loading) return
            this.loading = true

            // 模拟API请求
            setTimeout(() => {
                // 这里应该使用真实API接口
                const newItems = Array.from({ length: 10 }, (_, i) => {
                    const index = this.postList.length + i
                    return {
                        id: index + 1,
                        userId: index + 100,
                        userName: index % 2 === 0 ? 'SenLinMu' : '拼凑Coder',
                        userAvatar: `https://i.pravatar.cc/100?u=${index + 200}`,
                        postTime: index % 2 === 0 ? 'IT·5小时前' : '前端·5小时前',
                        location: index % 3 === 0 ? this.location.city : null,
                        tag: index % 3 === 0 ? '新人报道' : null,
                        content: index % 2 === 0 ? '下班回家了吗？' : '水一条，不知道还能待多久',
                        comments: Math.floor(Math.random() * 20),
                        likes: Math.floor(Math.random() * 10),
                        isLiked: false
                    }
                })

                this.postList = [...this.postList, ...newItems]
                this.loading = false
            }, 500)
        },

        // 加载关注页帖子列表
        loadFollowList() {
            if (this.loading) return
            this.loading = true

            // 模拟API请求
            setTimeout(() => {
                // 这里应该使用真实API接口
                const newItems = Array.from({ length: 5 }, (_, i) => {
                    const index = this.followList.length + i
                    return {
                        id: index + 1,
                        userId: index + 100,
                        userName: `${['时尚博主', '美食家', '旅行家', '摄影师', '生活家'][index % 5]}`,
                        userAvatar: `https://i.pravatar.cc/100?u=${index + 500}`,
                        createTime: `${Math.floor(Math.random() * 24)}小时前`,
                        location: index % 3 === 0 ? this.location.city : null,
                        title: `${['分享我的环球旅行', '今天做了超好吃的甜点', '分享一组街拍照片', '最近发现的好物分享', '周末度假小记'][index % 5]}`,
                        content: `${['这次旅行真的太棒了，遇到了很多有趣的人和事...', '这个配方我试了好多次终于成功了，分享给大家...', '这组照片是在城市的小角落拍的，希望大家喜欢...', '最近发现了这些超实用的好物，推荐给大家...', '周末去了附近的小镇，环境真的太美了...'][index % 5]}`,
                        images: [
                            `https://picsum.photos/300/400?random=${index + 600}`,
                            `https://picsum.photos/300/400?random=${index + 601}`,
                            `https://picsum.photos/300/400?random=${index + 602}`
                        ].slice(0, Math.floor(Math.random() * 3) + 1),
                        likes: Math.floor(Math.random() * 100),
                        comments: Math.floor(Math.random() * 50),
                        isLiked: false
                    }
                })

                this.followList = [...this.followList, ...newItems]
                this.loading = false
            }, 500)
        },

        // 点赞
        likePost(post) {
            // 应该调用API
            post.isLiked = !post.isLiked
            post.likes += post.isLiked ? 1 : -1
            this.$toast(post.isLiked ? '已点赞' : '已取消点赞')
        },

        // 监听滚动，加载更多内容
        onScroll() {
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            const clientHeight = document.documentElement.clientHeight
            const scrollHeight = document.documentElement.scrollHeight

            if (scrollTop + clientHeight >= scrollHeight - 50) {
                if (this.topTab === 'discover') {
                    this.loadPostList()
                } else {
                    this.loadFollowList()
                }
            }
        }
    },

    mounted() {
        window.addEventListener('scroll', this.onScroll)

        // 初始加载关注列表
        this.loadFollowList()
    },

    beforeDestroy() {
        window.removeEventListener('scroll', this.onScroll)
    }
}
</script>

<style scoped>
.square-container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 50px;
}

/* 顶部标签 */
.top-tabs {
    display: flex;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    padding: 8px 40px;
    position: sticky;
    top: 0;
    z-index: 10;
}

.tab {
    position: relative;
    flex: 1;
    text-align: center;
    padding: 8px 0;
    font-size: 16px;
    color: #666;
}

.tab.active {
    color: #1989fa;
    font-weight: 500;
}

.tab.active::after {
    content: '';
    position: absolute;
    bottom: -9px;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 3px;
    background-color: #1989fa;
    border-radius: 1.5px;
}

/* 搜索栏 */
.search-bar {
    display: flex;
    align-items: center;
    margin: 12px 16px;
    padding: 8px 12px;
    background-color: #f1f1f1;
    border-radius: 16px;
    color: #999;
}

.search-bar .van-icon {
    margin-right: 8px;
}

/* 推荐圈子 */
.circle-section {
    background-color: #fff;
    padding: 16px;
    margin-bottom: 8px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.section-title {
    font-size: 16px;
    font-weight: 500;
}

.section-more {
    font-size: 14px;
    color: #999;
}

.circle-list {
    display: flex;
    overflow-x: auto;
    white-space: nowrap;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 8px;
}

.circle-list::-webkit-scrollbar {
    display: none;
}

.circle-item {
    margin-right: 16px;
    text-align: center;
}

.circle-icon {
    position: relative;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 8px;
}

.circle-icon img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.circle-tag {
    position: absolute;
    top: 0;
    right: 0;
    background-color: #1989fa;
    color: white;
    font-size: 10px;
    border-radius: 8px;
    padding: 1px 4px;
}

.circle-name {
    font-size: 12px;
    max-width: 60px;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 排序栏 */
.sort-bar {
    display: flex;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    padding: 0 16px;
}

.sort-item {
    padding: 12px 12px;
    margin-right: 12px;
    font-size: 14px;
    color: #666;
}

.sort-item.active {
    color: #1989fa;
    font-weight: 500;
}

/* 帖子列表 */
.post-list {
    background-color: #f5f5f5;
    padding: 8px;
}

.post-item {
    margin-bottom: 8px;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
}

.post-user {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
    object-fit: cover;
}

.user-info {
    flex: 1;
}

.user-name {
    font-size: 15px;
    font-weight: 500;
    margin-bottom: 4px;
}

.post-time {
    font-size: 12px;
    color: #999;
}

.more-btn {
    padding: 4px;
    font-size: 18px;
    color: #999;
}

.post-content {
    margin-bottom: 16px;
}

.post-tag {
    display: inline;
    color: #1989fa;
    font-size: 14px;
    margin-right: 4px;
}

.post-text {
    display: inline;
    font-size: 14px;
    line-height: 1.4;
}

.post-images {
    display: flex;
    gap: 4px;
    margin-top: 12px;
}

.post-images img {
    width: 33.33%;
    height: 100px;
    object-fit: cover;
    border-radius: 4px;
}

.post-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.action-item {
    display: flex;
    align-items: center;
    margin-left: 16px;
    color: #999;
    font-size: 14px;
}

.action-item .van-icon {
    margin-right: 4px;
    font-size: 16px;
}

.action-item .liked {
    color: #1989fa;
}

.loading-more {
    text-align: center;
    padding: 16px 0;
    color: #999;
}

.empty-follow {
    padding: 40px 0;
}

.empty-btn {
    margin-top: 16px;
}
</style>